package m.jclecai.com.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.data.Lecai_SDK;
import m.jclecai.com.utils.AppUtils;

/**
 *  加载富文本
 */
public class WebLoadRichTextActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.web_tendecy_view)
    WebView web_tendecy_view;
    @BindView(R.id.pb_progress)
    ProgressBar pbProgress;

    @BindView(R.id.sv)
    ScrollView sv;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.tv_title)
    TextView tv_title;


    private String code;
    private boolean isLocol;

    @Override
    public int getContentView() {
        return R.layout.activity_web_helper;
    }


    @Override
    public void initView() {
        Intent intent = getIntent();
        code = intent.getStringExtra("code");
        isLocol = intent.getBooleanExtra("isLocal", false);
        String title = intent.getStringExtra("title");
        setTitle(title);
        leftOptionText("");
        allowBodyCoverTitle(intent.getBooleanExtra("allowBodyCoverTitle", false));
        sv.post(new Runnable() {
            @Override
            public void run() {
                sv.fullScroll(ScrollView.FOCUS_UP);
            }
        });
        tv_title.setText(Lecai_SDK.web_title);
        tv_type.setText(Lecai_SDK.web_type);
    }

    WebSettings webSettings = null;
    @Override
    public void initData() {
        //webView的设置
        webSettings = web_tendecy_view.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);//适应分辨率
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUserAgentString(webSettings.getUserAgentString());

        webSettings.setDatabaseEnabled(true);
        webSettings.setGeolocationEnabled(true);
        String dir = getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setDatabasePath(dir);
        webSettings.setGeolocationDatabasePath(dir);

        webSettings.setAppCacheEnabled(true);
        String cacheDir = getDir("cache", Context.MODE_PRIVATE).getPath();
        webSettings.setAppCachePath(cacheDir);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 10);
        webSettings.setAllowFileAccess(true);

        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);

        webSettings.setBuiltInZoomControls(false);
        //  webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);
        webSettings.setDefaultTextEncodingName("utf-8");
        DisplayMetrics displayMetrics = AppUtils.phoneDM(this);
        if (displayMetrics.widthPixels<540){
            webSettings.setTextZoom(125);
        }else if (displayMetrics.widthPixels>=540&&displayMetrics.widthPixels<=720){
            webSettings.setTextZoom(250);
        }else {
            webSettings.setTextZoom(300);
        }


        web_tendecy_view.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                web_tendecy_view.getSettings().setBlockNetworkImage(false);
                sv.post(new Runnable() {
                    @Override
                    public void run() {
                        sv.fullScroll(ScrollView.FOCUS_UP);
                    }
                });
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                sv.post(new Runnable() {
                    @Override
                    public void run() {
                        sv.fullScroll(ScrollView.FOCUS_UP);
                    }
                });
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

               // http://view.inews.qq.com/a/20180514A0Z44X00

                    startActivity(WebHelperActivity.getInstance(WebLoadRichTextActivity.this,url,false,"新闻详情"));
                    finish();
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        //去掉webView右边的滚动条
        web_tendecy_view.setHorizontalScrollBarEnabled(false);//水平不显示
        web_tendecy_view.setVerticalScrollBarEnabled(false); //垂直不显示
        web_tendecy_view.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
//                if (newProgress == 100) {
//                    // 网页加载完成
//                    pbProgress.setVisibility(View.GONE);
//
//                } else {
//                    // 加载中
//                    pbProgress.setProgress(newProgress);
//
//                }
                super.onProgressChanged(view, newProgress);
            }
        });
        //加载url
        initWebView(code);


    }


    private void initWebView(String content){
        web_tendecy_view.getSettings().setJavaScriptEnabled(true);
        web_tendecy_view.getSettings().setBuiltInZoomControls(true);
        web_tendecy_view.getSettings().setDisplayZoomControls(false);
        web_tendecy_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果

        web_tendecy_view.getSettings().setDefaultTextEncodingName("UTF-8") ;
        web_tendecy_view.getSettings().setBlockNetworkImage(false);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            web_tendecy_view.getSettings().setMixedContentMode(web_tendecy_view.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
        web_tendecy_view.loadDataWithBaseURL("http://avatar.csdn.net",getNewContent(content),"text/html", "UTF-8", null);
    }

    private String getNewContent(String htmltext){

        Document doc= Jsoup.parse(htmltext);
        Elements elements=doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width","100%").attr("height","auto");
        }

        return doc.toString();
    }


    @Override
    public void onClick(View v) {
        onFinish();
    }


    public static Intent getInstance(Context context,String url,boolean isLocol,String title){

        Intent intent = new Intent(context, WebLoadRichTextActivity.class);
        intent.putExtra("code",url);
        intent.putExtra("isLocal",isLocol);
        intent.putExtra("title",title);
        return intent;
    }

}
